<template>
  <el-dialog :title="dataForm.id ? $t('common.editBtn') : $t('common.addBtn') " v-model="visible" width="870"
    :close-on-click-modal="false" draggable>
    <el-form :model="dataForm" :rules="dataRules" label-width="145px" ref="dataFormRef" v-loading="loading">
      <el-row :gutter="20">

        <el-col :span="12" class="mb-6">
          <el-form-item :label="'SAP ' + $t('invLocation.sapPlantCode')" prop="sapPlantCode">
            <el-input clearable :placeholder="$t('wms.pleaseEnter') + ' SAP '+  $t('invLocation.sapPlantCode')"
              v-model="dataForm.sapPlantCode" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb-6">
          <el-form-item :label="'SAP ' + $t('invLocation.sapPlantName')" prop="sapPlantName">
            <el-input clearable :placeholder="$t('wms.pleaseEnter') + ' SAP '+  $t('invLocation.sapPlantName')"
              v-model="dataForm.sapPlantName" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb-6">
          <el-form-item :label="'SAP ' + $t('invLocation.sapWarehouseCode')" prop="sapWarehouseCode">
            <el-input clearable :placeholder="$t('wms.pleaseEnter') + ' SAP '+  $t('invLocation.sapWarehouseCode')"
              v-model="dataForm.sapWarehouseCode" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb-6">
          <el-form-item :label="'SAP ' + $t('invLocation.sapWarehouseName')" prop="sapWarehouseName">
            <el-input clearable :placeholder="$t('wms.pleaseEnter') + ' SAP '+  $t('invLocation.sapWarehouseName')"
              v-model="dataForm.sapWarehouseName" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb-6">
          <el-form-item :label="'MES ' + $t('mes.warehouseCode')" prop="warehouseCode">
            <el-select v-model="dataForm.warehouseCode" multiple collapse-tags collapse-tags-tooltip clearable filterable
              @change="changeWarehouseCode" :placeholder="$t('wms.select') + ' MES ' + $t('mes.warehouseCode')">
              <el-option v-for="item in optionsWarehouse" :key="item.warehouseCode"
                :label="item.warehouseCode + ' - ' + item.warehouseName" :value="item.warehouseCode">
                <span style="float: left">{{ item.warehouseCode }}</span>
                <span style="
                    float: right;
                    color: var(--el-text-color-secondary);
                    font-size: 13px;
                  ">
                  {{ item.warehouseName }}
                </span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb-6">
          <el-form-item :label="'MES ' + $t('mes.warehouseName')" prop="warehouseName">
            <el-input clearable disabled :placeholder="$t('wms.pleaseEnter') + ' MES '+  $t('mes.warehouseName')"
              v-model="dataForm.warehouseName" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false" icon="Close">{{ $t('common.cancelButtonText') }}</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading" icon="Check">{{ $t('common.confirmButtonText')
          }} </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">

import {useDict} from "/@/hooks/dict";
import {addWarehouse, updateWarehouse, fetchWarehouseList} from "/@/api/platform/wms/warehouse";
import {useMessage} from "/@/hooks/message";
import {useI18n} from "vue-i18n";

const {t} = useI18n();

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);

//获取仓库
const optionsWarehouse = ref([])
onMounted(() => {
    fetchWarehouseList(
      {
        current : 1, 
        size: 100
      }
    ).then(res => {
        optionsWarehouse.value = res.data.records
    })
})
// 当选择了仓库后，更新dataForm
const changeWarehouseCode = (val: any[]) => {  
  // 清空情况：val 为空数组（多选模式下取消所有选项）
  if (!val || val.length === 0) {
    dataForm.warehouseName = [];
  } 
  else {
    // 非空情况：val 包含选中的仓库代码
    const selectedWarehouses = optionsWarehouse.value.filter(item => val.includes(item.warehouseCode));
    dataForm.warehouseName = selectedWarehouses.map(item => item.warehouseName);
  }
};

// 定义form数据
const dataForm = reactive({
  id: null,
  warehouseCode: [] as String[] | undefined,
  warehouseName: [] as String[] | undefined,
  sapPlantCode: '' as String | undefined,
  sapPlantName: '' as String | undefined,
  sapWarehouseCode: '' as String | undefined,
  sapWarehouseName: '' as String | undefined
});

// 定义表单校验规则
const dataRules = reactive({
  warehouseCode: [
    {required: true, message: t('wms.select') + ' MES '+  t('mes.warehouseCode'), trigger: 'blur'},
  ],
  warehouseName: [
    {required: true, message: t('wms.pleaseEnter') + ' MES '+  t('mes.warehouseName'), trigger: 'blur'},
  ],
  sapPlantCode: [
    {required: true, message: t('wms.pleaseEnter') + ' SAP '+  t('invLocation.sapPlantCode'), trigger: 'blur'},
  ],
  sapPlantName: [
    {required: true, message: t('wms.pleaseEnter') + ' SAP '+  t('invLocation.sapPlantName'), trigger: 'blur'},
  ],
  sapWarehouseCode: [
    {required: true, message: t('wms.pleaseEnter') + ' SAP '+  t('invLocation.sapWarehouseCode'), trigger: 'blur'},
  ],
  sapWarehouseName: [
    {required: true, message: t('wms.pleaseEnter') + ' SAP '+  t('invLocation.sapWarehouseName'), trigger: 'blur'},
  ]
})

// 通知父组件刷新
const emit = defineEmits(['refresh']);

// 提交表单
const onSubmit = async () => {
  loading.value = true;
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      loading.value = false;
      return false;
    }
    if (dataForm.id) {
      // id存在 则更新数据
      updateWarehouse(dataForm).then((res: any) => {
        if (res.code !== 0) {
          useMessage().error(res.msg);
          return
        }
        loading.value = false;
        visible.value = false;
        emit('refresh');
        // 成功提示
        useMessage().success("更新成功!");
      }).catch(error => {
        loading.value = false;
        useMessage().error(error.msg);
      })

    } else {
      // dataForm将除了id以外的数据解构出来
      const {id, ...submitData} = dataForm;
      // id不存在 则新增数据
      addWarehouse(submitData).then((res: any) => {
        if (res.code !== 0) {
          useMessage().error(res.msg);
          return
        }
        loading.value = false;
        visible.value = false;
        emit('refresh');
        // 成功提示
        useMessage().success(t('common.addSuccessText'));
      }).catch(error => {
        loading.value = false;
        useMessage().error(error.msg);
      })
    }
  })
};

// 打开弹框
const openAddDialog = () => {
  visible.value = true;
  dataForm.id = undefined

  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });

};

// 编辑弹框
const openEditDialog = (data: any) => {
  visible.value = true;
  // 将data中的数据解构到dataForm中
  Object.assign(dataForm, data);
}

// 暴露变量
defineExpose({
  openAddDialog, openEditDialog
});

</script>

<style scoped lang="scss">

</style>